package controller;

import controller.util.JsfUtil;
import facade.FornecedorFacade;
import facade.EnderecoFacade;
import facade.TelefoneFacade;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import modelo.Fornecedor;
import modelo.Endereco;
import modelo.Pessoa;
import modelo.Telefone;

@ManagedBean(name = "fornecedorController")
@SessionScoped
public class FornecedorController implements Serializable {

    private Fornecedor current;
    private Endereco currentEndereco;
    private Telefone currentTelefone;
    
    private DataModel items = null;
    private DataModel itemsEndereco = null;
    private DataModel itemsTelefone = null;
    
    private List<Endereco> listEnderecoAUX;
    private List<Telefone> listTelefoneAUX;
    
    @EJB
    private facade.FornecedorFacade ejbFacade;
    @EJB
    private facade.EnderecoFacade ejbEnderecoFacade;
    @EJB
    private facade.TelefoneFacade ejbTelefoneFacade;
    
    private String maskCgc = "999.999.999-99";

    public FornecedorController() {
    }

    public Pessoa getSelected() {
        if (current == null) {
            current = new Fornecedor();
        }
        return current;
    }

    public Endereco getEnderecoSelected() {
        if (currentEndereco == null) {
            currentEndereco = new Endereco();
        }
        return currentEndereco;
    }

    public Telefone getTelefoneSelected() {
        if (currentTelefone == null) {
            currentTelefone = new Telefone();
        }
        return currentTelefone;
    }

    private FornecedorFacade getFacade() {
        return ejbFacade;
    }

    private EnderecoFacade getEnderecoFacade() {
        return ejbEnderecoFacade;
    }

    private TelefoneFacade getTelefoneFacade() {
        return ejbTelefoneFacade;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Fornecedor) getItems().getRowData();
        recreateModelEndereco();
        recreateModelTelefone();
        listEnderecoAUX = getEnderecoFacade().findByPessoa(current);
        listTelefoneAUX = getTelefoneFacade().findByPessoa(current);
        return "View";
    }

    public String prepareCreate() {
        current = new Fornecedor();
        current.setTipoPessoa("J");
        recreateModelEndereco();
        listEnderecoAUX = new ArrayList<Endereco>();
        recreateModelTelefone();
        listTelefoneAUX = new ArrayList<Telefone>();
        return "Create";
    }

    public void prepareCreateEndereco() {
        currentEndereco = new Endereco();
    }

    public void prepareCreateTelefone() {
        currentTelefone = new Telefone();
    }

    public String create(ActionEvent actionEvent) {
        try {
            current.setDataInclusao(new Date());
//            current.setEnderecoList(listEnderecoAUX);
            getFacade().create(current);
            for (Endereco e : listEnderecoAUX){
                e.setPessoa(current);
                getEnderecoFacade().create(e);
            }
            for (Telefone t : listTelefoneAUX){
                t.setPessoa(current);
                getTelefoneFacade().create(t);
            }
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FornecedorCreated"));
            recreateModel();
            recreateModelEndereco();
            recreateModelTelefone();
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public void createEndereco(ActionEvent actionEvent) {
 //       try {
//            getEnderecoFacade().create(currentEndereco);
            listEnderecoAUX.add(currentEndereco);
            itemsEndereco = new ListDataModel(listEnderecoAUX);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EnderecoCreated"));
 /*       } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }*/
    }

    public void createTelefone(ActionEvent actionEvent) {
            listTelefoneAUX.add(currentTelefone);
            itemsTelefone = new ListDataModel(listTelefoneAUX);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("TelefoneCreated"));
    }

    public String prepareEdit() {
        current = (Fornecedor) getItems().getRowData();
        recreateModelEndereco();
        listEnderecoAUX = getEnderecoFacade().findByPessoa(current);
        recreateModelTelefone();
        listTelefoneAUX = getTelefoneFacade().findByPessoa(current);
        return "Edit";
    }

    public void prepareEditEndereco(ActionEvent actionEvent) {
        currentEndereco = (Endereco) getItemsEndereco().getRowData();
    }

    public void prepareEditTelefone(ActionEvent actionEvent) {
        currentTelefone = (Telefone) getItemsTelefone().getRowData();
    }

    public String update() {
        try {
            for (Endereco e : listEnderecoAUX){
                e.setPessoa(current);
            }
            for (Telefone t : listTelefoneAUX){
                t.setPessoa(current);
            }
            current.setEnderecoList(listEnderecoAUX);
            current.setTelefones(listTelefoneAUX);
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FornecedorUpdated"));
            return prepareList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public void updateEndereco(ActionEvent actionEvent) {
        try {
            listEnderecoAUX.set(listEnderecoAUX.indexOf(currentEndereco), currentEndereco);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EnderecoUpdated"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public void updateTelefone(ActionEvent actionEvent) {
        try {
            listTelefoneAUX.set(listTelefoneAUX.indexOf(currentTelefone), currentTelefone);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("TelefoneUpdated"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public String destroy() {
        current = (Fornecedor) getItems().getRowData();
        current.setEnderecoList(listEnderecoAUX);
        current.setTelefones(listTelefoneAUX);
        performDestroy();
        recreateModel();
        return "List";
    }

    public void destroyEndereco(ActionEvent actionEvent) {
        currentEndereco = (Endereco) getItemsEndereco().getRowData();
        performDestroyEndereco();
        recreateModelEndereco();
    }

    public void destroyTelefone(ActionEvent actionEvent) {
        currentTelefone = (Telefone) getItemsTelefone().getRowData();
        performDestroyTelefone();
        recreateModelTelefone();
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FornecedorDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void performDestroyEndereco() {
 //       try {
//            getEnderecoFacade().remove(currentEndereco);
            listEnderecoAUX.remove(currentEndereco);
/*            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EnderecoDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }*/
    }

    private void performDestroyTelefone() {
            listTelefoneAUX.remove(currentTelefone);
    }

    public DataModel getItems() {
        if (items == null) {
            items = new ListDataModel(getFacade().findAll());
        }
        return items;
    }

    public DataModel getItemsEndereco() {
        if (itemsEndereco == null) {
            if (current.getIdPessoa() != null)
                itemsEndereco = new ListDataModel(listEnderecoAUX);
            else {
                itemsEndereco = new ListDataModel();
            }
        }
        return itemsEndereco;
    }

    public DataModel getItemsTelefone() {
        if (itemsTelefone == null) {
            if (current.getIdPessoa() != null)
                itemsTelefone = new ListDataModel(listTelefoneAUX);
            else {
                itemsTelefone = new ListDataModel();
            }
        }
        return itemsTelefone;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreateModelEndereco() {
        itemsEndereco = null;
    }

    private void recreateModelTelefone() {
        itemsTelefone = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    /**
     * @return the maskCgc
     */
    public String getMaskCgc() {
        return maskCgc;
    }

    /**
     * @param maskCgc the maskCgc to set
     */
    public void mudarCgc() {
        if(current.getTipoPessoa().equals("F")){
            this.maskCgc = "999.999.999-99";
        }else{
            this.maskCgc = "99.999.999/9999-99";
        }
    }

    @FacesConverter(forClass = Fornecedor.class)
    public static class FornecedorControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            FornecedorController controller = (FornecedorController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "fornecedorController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Fornecedor) {
                Fornecedor o = (Fornecedor) object;
                return getStringKey(o.getIdPessoa());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + FornecedorController.class.getName());
            }
        }
    }
}